package com.am.server.api.system.log.service.impl;

import com.am.server.api.system.log.dao.rbd.LogDao;
import com.am.server.api.system.log.model.dto.LogDto;
import com.am.server.api.system.log.model.dto.LogListQueryDto;
import com.am.server.api.system.log.model.dto.SaveLogDto;
import com.am.server.api.system.log.model.entity.LogEntity;
import com.am.server.api.system.log.model.mapper.LogMapper;
import com.am.server.api.system.log.service.LogService;
import com.am.server.common.annotation.transaction.Commit;
import com.am.server.common.annotation.transaction.ReadOnly;
import com.am.server.common.base.model.dto.PageDto;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 阮雪峰
 */
@Service
public class LogServiceImpl implements LogService {

    private final LogDao logDao;
    private final LogMapper logMapper;

    public LogServiceImpl(LogDao logDao, LogMapper logMapper) {
        this.logDao = logDao;
        this.logMapper = logMapper;
    }

    @Commit
    @Override
    public void save(SaveLogDto saveLogDto) {
        LogEntity log = new LogEntity();
        log.setName(saveLogDto.getName());
        log.setOperate(saveLogDto.getOperate());
        log.setMenu(saveLogDto.getMenu());
        log.setIp(saveLogDto.getIp());
        log.setCreatedTime(LocalDateTime.now());
        log.setExtend(saveLogDto.getExtend());
        logDao.save(log);
    }

    @ReadOnly
    @Override
    public PageDto<LogDto> find(LogListQueryDto query) {
        Page<LogEntity> page = logDao.findAll(query);
        return new PageDto<LogDto>()
                .setPageSize(query.getPageSize())
                .setPage(query.getPage())
                .setTotal((int) page.getTotalElements())
                .setTotalPage(page.getTotalPages())
                .setRows(page.getContent().stream().map(logMapper::toDto).toList());
    }
}
